package com.neulogistics.contrib.usercenter.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.contrib.usercenter.api.application.converter.UserPOVMConverter;
import com.neulogistics.contrib.usercenter.api.application.converter.UserQueryPOConverter;
import com.neulogistics.contrib.usercenter.api.application.viewmodel.UserViewModel;
import com.neulogistics.contrib.usercenter.infrastructure.persistence.orm.po.UserPO;
import com.neulogistics.contrib.usercenter.infrastructure.persistence.orm.service.IUserPOService;
import com.neulogistics.contrib.usercenter.api.application.converter.PageVMConverter;
import com.neulogistics.infrastructure.common.query.PageViewModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserQueryService implements IUserQueryService {
    @Resource
    private IUserPOService userPOService;

    @Override
    public UserViewModel getUserById(Integer id) {
        UserPO userPO = userPOService.getById(id);
        UserViewModel userViewModel = UserPOVMConverter.POToVM(userPO);
        return userViewModel;
    }

    @Override
    public Page<UserViewModel> getUserByPage(UserQuery userQuery) {
        // 提取查询条件
        UserPO userPOQuery = UserQueryPOConverter.queryToPO(userQuery);
        long current = userQuery.getPageNum();
        long pageSize = userQuery.getPageSize();

        // 构建查询条件包装器
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>(userPOQuery);

        // 执行分页查询
        Page<UserPO> page = userPOService.page(new Page<>(current, pageSize), queryWrapper);

        // 构建结果
        Page<UserViewModel> viewModelPage = new Page<>(current, pageSize);
        List<UserViewModel> viewModelList = page.getRecords().stream()
                .map(UserPOVMConverter::POToVM)
                .collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());

        return viewModelPage;
    }
}
